package com.sports.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sports.entity.*;
import com.sports.service.ItemService;
import com.sports.service.RegisterService;
import com.sports.service.ScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("register")
public class RegisterController {
    @Autowired
    private RegisterService registerService;
    @Autowired
    private ScoreService scoreService;
    @Autowired
    private ItemService itemService;

    //新增报名信息
    //报名状态status默认为0
    @PostMapping("addRegister/{itemId}")
    public Map<String,Object> addRegister(HttpSession session, @PathVariable Integer itemId) {
        Map<String,Object> map = new HashMap<>();
        Athletes athletes = (Athletes) session.getAttribute("user");
        Integer athletesId = athletes.getAthletesId();
        List<Register> registerList = registerService.list(Wrappers.<Register>lambdaQuery().eq(Register::getAthletesId, athletesId));
        // 遍历registerList并获取每个元素的itemId
        List<Integer> itemIds = new ArrayList<>();
        registerList.forEach(register -> itemIds.add(register.getItemId()));
        // 判断是否存在相同的itemId
        if (!itemIds.contains(itemId)){
            Register register = new Register();
            register.setAthletesId(athletes.getAthletesId());
            register.setStatus(0);
            register.setItemId(itemId);
            registerService.save(register);
            map.put("message","success");
        } else {
            map.put("message","failed");
        }
        return map;
    }

    //报名审批
    //报名状态status修改为1，同时向t_score成绩表中增加athletes_id和item_id两个字段
    @PostMapping("approve/{registerId}")
    public Map<String,Object> approve(@PathVariable Integer registerId) {
        Map<String,Object> map = new HashMap<>();
        Register register = registerService.getById(registerId);
        Integer status = register.getStatus();
        if (status == 0){
            register.setStatus(1);
            registerService.updateById(register);
            Score score = new Score();
            score.setAthletesId(register.getAthletesId());
            score.setItemId(register.getItemId());
            scoreService.save(score);
            map.put("message","success");
        }else {
            map.put("message","failed");
        }
        return map;
    }

    //删除报名信息
    @DeleteMapping("removeRegister/{registerId}")
    public Map<String,Object> removeRegister(@PathVariable Integer registerId){
        Map<String,Object> map = new HashMap<>();
        registerService.removeById(registerId);
        map.put("message","success");
        return map;
    }

    //修改报名信息
    @PutMapping("updateRegister")
    public Map<String,Object> updateRegister(@RequestBody Register register) {
        Map<String,Object> map = new HashMap<>();
        registerService.updateById(register);
        map.put("message","success");
        return map;
    }

    //查询所有报名信息（分页）
    @GetMapping("showAllRegister/{pageNum}/{pageSize}")
    public Map<String,Object> showAllRegister(@RequestParam(value = "name", required = false)  String name,
                                              @PathVariable(value = "pageNum") int pageNum,
                                              @PathVariable(value = "pageSize") int pageSize){
        Map<String,Object> map = new HashMap<>();
        //分页
        Page<RegisterDTO> page = new Page<>(pageNum, pageSize);
        IPage<RegisterDTO> registerDTOPage = registerService.showRegister(page,name);
        //获取分页结果
        List<RegisterDTO> registerDTOS = registerDTOPage.getRecords();
        long total = registerDTOPage.getTotal();
        map.put("message", "success");
        map.put("registerList",registerDTOS);
        map.put("pageSize", pageSize);
        map.put("pageNum", pageNum);
        map.put("total", total);
        return map;
    }

    //根据运动员id查询该运动员的报名信息(分页)
    @GetMapping("showRegisterByAthletesId/{pageNum}/{pageSize}")
    public Map<String,Object> showRegisterByAthletesId(@RequestParam(value = "name", required = false)  String name,
                                                       @PathVariable(value = "pageNum") int pageNum,
                                                       @PathVariable(value = "pageSize") int pageSize, 
                                                       HttpSession session){
        Map<String,Object> map = new HashMap<>();
        Integer role = (Integer) session.getAttribute("role");
        Integer athletesId = null;
        if (role == 2) {
            Athletes athletes = (Athletes) session.getAttribute("user");
            athletesId = athletes.getAthletesId();
        }
        // 分页
        Page<RegisterDTO> page = new Page<>(pageNum, pageSize);
        IPage<RegisterDTO> registerDTOPage = registerService.showRegisterByAthletesId(page, athletesId,role, name);
        // 获取分页结果
        List<RegisterDTO> registerDTOS = registerDTOPage.getRecords();
        long total = registerDTOPage.getTotal();
        map.put("message", "success");
        map.put("registerList", registerDTOS);
        map.put("pageSize", pageSize);
        map.put("pageNum", pageNum);
        map.put("total", total);
        return map;
    }

    //查比赛项目
    @GetMapping("list/{pageNum}/{pageSize}")
    public Map list(
            @RequestParam(value = "name", required = false)  String name,
            @PathVariable(value = "pageNum") int pageNum,
            @PathVariable(value = "pageSize") int pageSize){
        Map map = new HashMap();
        LambdaQueryWrapper<Item> wrapper = new LambdaQueryWrapper<Item>();
        if (!ObjectUtils.isEmpty(name)) {
            wrapper.like(Item::getItemName, name);
        }
        Page<Item> page = new Page<>(pageNum, pageSize);
        IPage<Item> page1 = itemService.page(page, wrapper);
        List<Item> list = page1.getRecords();
        long page1Size = page1.getSize();
        long current = page1.getCurrent();
        long total = page1.getTotal();
        map.put("message","success");
        map.put("list",list);
        map.put("pageSize",page1Size);
        map.put("pageNum",current);
        map.put("total",total);
        return map;
    }


}
